package com.changgou.service.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changgou.goods.pojo.*;
import com.changgou.goods.pojo.Spu;
import com.changgou.service.goods.dao.BrandMapper;
import com.changgou.service.goods.dao.CategoryMapper;
import com.changgou.service.goods.dao.SkuMapper;
import com.changgou.service.goods.dao.SpuMapper;
import com.changgou.service.goods.service.SpuService;
import com.changgou.utils.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id){
        Goods goods = new Goods();
        Spu spu = spuMapper.selectByPrimaryKey(id);
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spu.getId());
        List<Sku> skuList = skuMapper.selectByExample(example);
        goods.setSpu(spu);
        goods.setSkuList(skuList);
        return goods;
    }

    @Override
    public Spu findSpuById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 增加
     * @param goods
     */
    @Override
    @Transactional
    public void add(Goods goods){
        Spu spu = goods.getSpu();
        spu.setId(idWorker.nextId()+"");
        spu.setIsDelete("0");
        spu.setIsMarketable("0");
        spu.setStatus("0");
        System.out.println(spu);
        spuMapper.insertSelective(spu);
        this.saveSkuList(goods);
    }

    private void saveSkuList(Goods goods) {
        Spu spu = goods.getSpu();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            String name = spu.getName();
            if (StringUtils.isEmpty(sku.getSpec()) || "".equals(sku.getSpec())) {
                sku.setSpec("{}");
            } else {
                Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                for (String spec : specMap.values()) {
                    name+= " " + spec;
                }
            }
            sku.setName(name);
            sku.setId(idWorker.nextId() + "");
            sku.setSpuId(spu.getId());
            sku.setCategoryName(category.getName());
            sku.setBrandName(brand.getName());
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
            skuMapper.insertSelective(sku);
            System.out.println(sku);
        }
    }


    /**
     * 修改
     * @param goods
     */
    @Override
    @Transactional
    public void update(Goods goods){
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKey(spu);
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        skuMapper.deleteByExample(example);
        this.saveSkuList(goods);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional
    public void delete(String id){
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if ("0".equals(spu.getIsMarketable())) {
            throw new RuntimeException("商品必须处于下架状态");
        }
        spu.setStatus("0");
        spu.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    @Override
    public void audit(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除");
        }
        spu.setIsMarketable("1");
        spu.setStatus("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public void pull(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除");
        }
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public void put(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        if (!"1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已删除");
        }
        spu.setIsDelete("0");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public void realDel(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (!"1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品处于未删除状态");
        }
        spuMapper.deleteByPrimaryKey(spu);
    }


    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 商品id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 商品条码
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
            }
            // SKU名称
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }

        }
        return example;
    }
}
